define([
    "views/modules/popup",
    "helpers/network",
    "views/modules/form",
    "views/modules/table",
    "views/modules/pager",
    "models/products",
    "models/commonStatus",
    "libs/editor/ueditor.all"
], function (PopupView, Network, CommonForm, CommonTable, CommonPager, Products, CommonStatus) {

    var id = "";
    var TYPE = "ActualGoods";
    var keywordsId = id + "keywordsId";
    var supplierSelectorId = id + "supplierSelectorId";
    var categorySelectorId = id + "categorySelectorId";
    var windowsId = id + "window";
    var formId = id + "form";
    var searchFormId = id + "searchForm";
    var tableId = id + "table";
    var attrFormId = id + "attrForm";
    var basicAttrFormId = id + "basicAttrForm";
    var pagerId = id + "pager";
    var totalCountsId = id + "totalCounts";
    var pageIndex = 1, pageCounts;
    var uEditor;
    var uEditorId = id + 'ueditor';
    var uEditorConfig = {
        UEDITOR_HOME_URL: "libs/editor/",
        serverUrl: Network.url.imgUploadUrl + "/file/ueditor.do?group=goodsDetail",
        initialFrameHeight: 520,
        autoHeightEnabled: false,
        toolbars: [
            ['fullscreen', 'source', '|', 'undo', 'redo', '|', 'justifyleft','justifyright','justifycenter','justifyjustify', '|','template','|','bold', 'italic', 'underline', 'forecolor', 'backcolor', 'fontborder', 'strikethrough', '|', 'fontsize', 'lineheight', '|', 'link', '|', 'simpleupload', 'insertimage',]
        ]
    };

    var onTableReady = function (page) {
        page = page || 1;
        // var searchForm = $$(searchFormId).getValues();
        var obj = {
            params: {
            },
            size: 20,
            page: page,
            sort: ["seq,desc","creationTime,desc"]
        };
        Network.ajax("/ContentArticleView.queryAll.query", obj, function (ret) {
            $$(tableId).clearAll();
            $$(tableId).parse(ret.data.content);
            CommonPager.refreshPager(page, ret.data.totalPages);
            $$(totalCountsId).setValue(ret.data.totalElements + "条数据, 共" + ret.data.totalPages + "页");
        });
        pageIndex = page ? page : 1
    };

    var onSubmit = function (itemId) {
        if (!$$(formId).validate() || !uEditor.getContent()) {
            webix.message("信息填写有误, 请仔细录入...");
            return
        }
        var itemValues = _.assign($$(formId).getValues(), {
            content: uEditor.getContent().toApiUrlImageSrcContent(),
            lastModifyTime: new Date()
        });
        var obj = {
            data: {
                id: itemId || undefined,
                content: itemValues.content,
                title:itemValues.title,
                tag:itemValues.tag,
                seq:itemValues.seq
            }
        };

        Network.ajax(itemId ? "/ContentArticleTransactor.updateInfo.command" : "/ContentArticleTransactor.create.command", obj, function (ret) {
            var obj1 = {
                data: {
                    id: ret.data
                }
            };
            Network.ajax("/ContentArticleTransactor.publish.command", obj1, function (ret) {
                closeWindow();
                onTableReady(pageIndex);
            })
        })
    };

    var onWindowReady = function (item) {
        uEditor = UE.getEditor(uEditorId, uEditorConfig);
        uEditor.addListener('ready', function (state) {
            if (item && item.content) {
                uEditor.setContent(item.content.toApiUrlImageSrcContent());
            }
        });
    };

    var closeWindow = function () {
        if ($$(windowsId)) {
            $$(windowsId).close();
        }
        if (uEditor) {
            uEditor.destroy();
        }
    };

    var showWindow = function (title, item) {
        item = item || {data: {}};
        PopupView(windowsId, title, {
            rows: [
                {
                    cols: [
                        {
                            view: "scrollview", scroll: "y", paddingY: 5, paddingX: 10,
                            body: {
                                rows: [
                                    {
                                        view: "form", borderless: true, id: formId,
                                        rules: {
                                            // "cost": webix.rules.isNumber,
                                            // "salePrice": webix.rules.isNumber
                                        },
                                        rows: [
                                            {
                                                label: "文字标题", name: "title", view: "text",
                                                required: true, value: item.title || ""
                                            },
                                            {
                                                label: "标签", name: "tag", view: "text",disabled:true,
                                                required: true, value: item.tag || ""
                                            },
                                            {
                                                label: "序号", name: "seq", view: "text",
                                                required: true, value: item.seq || "0", placeholder: "序号越大越靠前"
                                            },
                                            {}
                                        ]
                                    }]
                            }
                        },
                        {
                            view: "scrollview", scroll: "y", paddingY: 5, paddingX: 10,
                            body: {
                                rows: [{
                                    name: "content", id: "content", borderless: true,
                                    template: function () {
                                        return "<div id='" + uEditorId + "'></div>"
                                    }
                                }]
                            }
                        }
                    ]
                },
                CommonForm.genSubmitButton(function () {
                    onSubmit(item.id)
                })
            ]
        }, 1200, 720, function () {
            onWindowReady(item)
        }, closeWindow);
    };

    var genSearchFormUI = function () {
        return {
            id: searchFormId, view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
            cols: [
                {},
                CommonForm.genKeywordsUI(keywordsId, "请输入商品名称进行查询", onTableReady),
                CommonForm.genSingleOptionSelector(categorySelectorId, "分类", Products.goodsCategories),
                CommonForm.genSingleOptionSelector(supplierSelectorId, "供应商", Products.data),
                CommonForm.genQueryButtonUI(onTableReady)
            ]
        }
    };

    var genOperationFormUI = function () {
        return {
            view: "form", css: "toolbar", paddingY: 5, paddingX: 10,
            cols: [
                {view: "label", label: "操作"},
                // {
                //     view: "button", label: "导出文件", width: 90, hidden: true,
                //     click: function () {
                //         // getExportData()
                //     }
                // },
                // {
                //     view: "button", label: "添加", width: 90,
                //     // hidden: Authority.hasNoAuth("GOODS_ADD"),
                //     click: function () {
                //         showWindow("添加")
                //     }
                // },
                {
                    view: "button", label: "修改", width: 90,
                    // hidden: Authority.hasNoAuth("GOODS_MODIFY"),
                    click: function () {
                        var item = $$(tableId).getSelectedItem();
                        if (item) showWindow("修改", item)
                    }
                },
            ]
        }
    };

    var genDataTableUI = function () {
        return {
            id: tableId, view: "datatable", resizeColumn: true, select: "row", data: [],
            complexData: true,
            // multiselect: true,
            // fixedRowHeight: false,
            ready: onTableReady,
            on: {
                onItemClick: function (id) {
                    // var item = this.getItem(id);
                    // if (item.status.id === "Online") {
                    //     $$("online").setValue("下架");
                    // } else if (item.status.id === "Offline") {
                    //     $$("online").setValue("上架");
                    // }
                    // $$("online").refresh();
                }
            },
            columns: [
                {
                    id: "id", header: "数据ID"
                },
                {
                    id: "title", header: "标题", fillspace: true,
                    // template: "#name#"
                },
                {
                    id: "tag", header: "标签", fillspace: true,
                    // template: "#data.name#"
                },
                {
                    id: "seq", header: "序号"
                    // template: "#data.cost#"
                },
                {
                    id: "status", header: "状态"
                    // template: "#data.status.value#"
                },
                ]
        }
    };

    var genFooterUI = function () {
        return {
            cols: [
                CommonPager.genPagerUI(pagerId, onTableReady),
                CommonPager.genTotalCountsUI(totalCountsId), {}
            ]
        }
    };

    return {
        $ui: {
            padding: 10,
            rows: [
                // genSearchFormUI(),
                genOperationFormUI(),
                genDataTableUI(),
                genFooterUI()
            ]
        }
    };

});